package ReefStats::Controller::Root;

use strict;
use warnings;
use base 'Catalyst::Controller::FormBuilder';
use DateTime;
use constant ALL_DOMAINS  => '-- All Domains --';
use constant ALL_USERS    => '-- All Users --';
use constant ALL_CLUSTERS => '-- All Clusters --';

#
# Sets the actions in this controller to be registered with no prefix
# so they function identically to actions created in MyApp.pm
#
__PACKAGE__->config->{namespace} = '';

=head1 NAME

ReefStats::Controller::Root - Root Controller for ReefStats

=head1 DESCRIPTION

[enter your description here]

=head1 METHODS

=cut

=head2 default

=cut

sub default : Private {
    my ( $self, $c ) = @_;

    $c->response->status('404');
    $c->stash->{template} = '404.tt2';
}

sub main : Local Form {
    my ( $self, $c ) = @_;

    my $form = $self->formbuilder;

    $c->stash->{cluster} =
      $form->param('cluster') eq ALL_CLUSTERS
      ? q{}
      : $c->model('ReefStatsDB::Cluster')->find( $form->param('cluster') )
      ->cluster;
    $c->stash->{cluster_alias} =
      $form->param('cluster') eq ALL_CLUSTERS
      ? q{}
      : $c->model('ReefStatsDB::Cluster')->find( $form->param('cluster') )
      ->alias;
    $c->stash->{domain} =
      $form->param('domain') eq ALL_DOMAINS
      ? q{}
      : $c->model('ReefStatsDB::Domain')->find( $form->param('domain') )
      ->domain;
    $c->stash->{user} =
      $form->param('user') eq ALL_USERS
      ? q{}
      : $c->model('ReefStatsDB::Users')->find( $form->param('user') )
      ->email_address;
    $c->stash->{start_date} = $form->param('start_date');
    $c->stash->{end_date}   = $form->param('end_date');
    $c->stash->{interval}   = $form->param('interval');

    $form->field(
        name    => 'cluster',
        options => [
            ALL_CLUSTERS,
            map { [ $_->id, $_->alias ] }
              $c->model('ReefStatsDB::Cluster')
              ->search( { visible => 1 }, { order_by => 'cluster' } )
        ]
    );
    $form->field(
        name    => 'user',
        options => [ ALL_USERS, ]
    );
    $form->field(
        name    => 'domain',
        options => [
            ALL_DOMAINS,
            map { [ $_->id, $_->domain ] }
              $c->model('ReefStatsDB::Domains')
              ->search( { visible => 1 }, { order_by => 'domain' } )
        ]
    );

    $c->stash->{top_spammed_emails} =
      $c->model('Maillog')->top_spammed_emails( $c->stash );

    $c->stash->{top_recipients} =
      $c->model('Maillog')->top_recipients( $c->stash );

    $c->stash->{top_domains_for_email} =
      $c->model('Maillog')->top_domains_for_email( $c->stash );

    $c->stash->{top_domains_for_spam} =
      $c->model('Maillog')->top_domains_for_spam( $c->stash );

    $c->stash->{top_actions} = $c->model('Maillog')->top_actions( $c->stash );

    $c->stash->{blacklists} = $c->model('Maillog')->blacklists( $c->stash );

    $c->stash->{template} = "main.tt2";
}

sub index : Private {
    my ( $self, $c ) = @_;
    if ( !$c->user ) {
        $c->res->redirect( $c->uri_for('/login') );
    }
    else {
        $c->res->redirect( $c->uri_for('/main') );
    }
}

sub access_denied : Private {
    my ( $self, $c ) = @_;
    $c->stash->{template} = 'access_denied.tt2';
}

sub login : Global Form {
    my ( $self, $c ) = @_;

    my $form = $self->formbuilder;

    return unless $form->submitted && $form->validate;

    if ( $c->login( $form->field('username'), $form->field('password') ) ) {
        $c->res->redirect( $c->uri_for('/main') );
        $c->detach();
    }
    else {
        $c->stash->{error} = 'Login failed.';
    }
}

sub logout : Global {
    my ( $self, $c ) = @_;
    $c->logout;
    $c->flash->{message} = 'Logged out.';
    $c->res->redirect( $c->uri_for('/') );
}

=pod

sub initial_reports {
    my $upper_date =
      DateTime->now()->set_time_zone('local')->subtract( days => 1 );
    my $lower_date = $upper_date->clone->subtract( days => 7 );
    $upper_date->set_hour(23)->set_minute(59)->set_second(59)
      ->set_nanosecond(999999999);
    $lower_date->set_hour(0)->set_minute(0)->set_second(0)->set_nanosecond(0);

    my $search_criteria =
      { day => { -between => [ $lower_date, $upper_date ] }, };

    my $case_logic = "case
when action in ('Allowed', 'Whitelisted') then action 
when action in ('Blocked', 'Deferred') then 'Blocked'
when action in ('Quarantined', 'Per-User Quarantine') then 'Quarantined'
else 'Other' 
end";

    my $rs = $maillog->search(
        {%$search_criteria},
        {
            select => [ 'cluster', 'day', $case_logic, { sum => 'number' } ],
            as       => [qw( cluster day action action_count )],
            group_by => [ qw( cluster day ), $case_logic ],
            order_by => [qw( cluster day action )],
        }
    );
}

=cut

=head2 end

Attempt to render a view, if needed.

=cut 

sub end : Private {
    my ( $self, $c ) = @_;
    $c->forward('ReefStats::View::TT');
}

=head1 AUTHOR

Joshua McAdams

=head1 LICENSE

This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

1;
